<!-- 控件创建表单 -->
<template>
  <a-modal
    v-model:visible="visible"
    class="form-modal"
    fullscreen
    :footer="false"
    :closable="false"
    :esc-to-close="false"
    title-align="center"
  >
    <div class="header">
      <a-menu
        class="menu"
        mode="horizontal"
        :default-selected-keys="['1']"
        @menu-item-click="menuItemClick($event)"
      >
        <a-menu-item key="1">基础设置</a-menu-item>
        <a-menu-item key="2">表单设计</a-menu-item>
        <a-menu-item key="3">打印配置</a-menu-item>
      </a-menu>
      <a-space>
        <a-button @click="next" type="outline">下一步</a-button>
        <a-button @click="chagangetest(2)" type="primary">保存</a-button>
        <a-button @click="goBack" type="outline">返回</a-button>
      </a-space>
    </div>
    <div class="content">
      <div class="main">
        <div class="base" v-show="menuSelected === '1'">
          <div class="base-form">
            <a-form :model="baseSetting" layout="vertical">
              <a-form-item field="name" label="人员模板名称">
                <a-input
                  size="large"
                  v-model="baseSetting.name"
                  placeholder="请输入模板名称"
                  allow-clear
                />
              </a-form-item>
              <a-form-item field="state" label="启用状态">
                <a-switch
                  v-model="baseSetting.enable"
                  :checked-value="1"
                  :unchecked-value="2"
                />
              </a-form-item>
              <a-form-item field="remark" label="描述">
                <a-textarea
                  v-model="baseSetting.remark"
                  placeholder="请输入"
                  show-word-limit
                  :max-length="300"
                  :auto-size="{
                    minRows: 5
                  }"
                  allow-clear
                />
              </a-form-item>
            </a-form>
          </div>
        </div>
        <!-- 表单设计 -->
        <div v-show="menuSelected === '2'">
          <setUPForm
            v-model:layout="rest"
            :tabCodeList="tabCodeList"
            :set-up-list="setUpList"
            ref="setUpFormRef"
          >
          </setUPForm>
        </div>
        <!-- 打印配置 -->
        <div class="print-set" v-show="menuSelected === '3'">
          <!-- 左侧是否显示打印配置开关列 -->
          <div class="form-check">
            <div
              class="check-item"
              v-for="(item, index) in formData[currIndex]?.componentModel"
              :key="index"
            >
              {{ item.name }}
              <a-switch
                v-model="item.show"
                :checked-value="1"
                :unchecked-value="0"
              />
            </div>
          </div>
          <Form
            class="form"
            :setUpList="formData[currIndex]?.componentModel"
            :layout="rest"
            :regex="regex"
            v-show="menuSelected === '3'"
          />
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { useSetupFormStore } from '@/store';
import { PostHumanTemplate } from '@/apis/management/human/baseSetting/humanSetting';
import clonedeep from 'lodash.clonedeep';
import setUPForm from '@/components/DynamicForms/set-up-form/index.vue';
import Form from '@/components/DynamicForms/rendering-form/form/index.vue';
import mitter from '@/utils/mitt';
import regex from '@/utils/regex';

const store = useSetupFormStore();
// 保存方法
const emit = defineEmits(['saveForm']);
const props = withDefaults(
  //参数说明
  defineProps<{
    patternId?: number; // 组织类型id
    data: any;
    tabCodeList?: string[]; // 具体要展示的tabCode
    // data: {
    //   id?: number;
    //   type?: number; // 表单类型 代表需求、订单等各种表单类型
    //   name?: string;
    //   form?: any;
    // };
  }>(),
  {
    tabCodeList: () => ['allComponent', 'baseComponent', 'businessComponent']
  }
);
const visible = ref(false);

// 基础设置的值
let baseSetting = ref({
  id: undefined,
  name: '', // 模板名称
  enable: 1, // 启用状态 1启用 2否
  remark: '', // 描述
  required: 2 // 是否设为默认模板 1是 2否， 新增默认为2
});

// 显示全屏弹框
const fullScreen = () => {
  visible.value = true;
};
const goBack = () => {
  baseSetting.value = {
    id: undefined,
    name: '', // 模板名称
    enable: 1, // 启用状态 1启用 2否
    remark: '', // 描述
    required: 2 // 是否设为默认模板 1是 2否， 新增默认为2
  };
  // store.tabList = [];
  store.templateId = undefined;
  console.log(baseSetting.value);
  visible.value = false;
};

// 表单是水平方式还是垂直，默认水平
let rest = ref('horizontal');

// 表单左侧的tabs
// const tabCodeList = reactive([
//   'allComponent',
//   'baseComponent',
//   'businessComponent'
// ]);

// 最上面的tabs
const menuSelected = ref('1');

const list = ref([]); // 储存基础设置的下拉框数据

// 获取类型信息
const getData = async () => {
  try {
    // const res = await GetJobTypeList();
    // list.value = dealTreeData(res);
    // console.log(list.value);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    // 新增叶子节点字段
    isLeaf: item.children ? false : true,
    // 新增是否能被选中字段，默认只有叶子节点可以选
    selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

// 下一步
const next = async () => {
  try {
    // 编辑
    if (baseSetting.value.id) {
      const temp = {
        id: baseSetting.value.id,
        isEnable: baseSetting.value.enable,
        required: baseSetting.value.required,
        name: baseSetting.value.name,
        remark: baseSetting.value.remark
      };
      console.log(temp);

      // await PutOrganizationTemplate(temp);
    }
    // 新增
    else {
      store.templateId = await PostHumanTemplate({
        level: 1, // 第一层默认传1
        personnelTemplate: {
          isEnable: baseSetting.value.enable,
          required: baseSetting.value.required,
          name: baseSetting.value.name,
          remark: baseSetting.value.remark
        }
      });
      store.tabList = [];

      const defaultCollection = [
        {
          name: '基础信息',
          sort: 0,
          templateId: store.templateId,
          required: 1
        },
        {
          name: '任职信息',
          sort: 1,
          templateId: store.templateId,
          required: 1
        }
      ];
      defaultCollection.forEach(async (item: any, index: number) => {
        const collectionId = await PostHumanTemplate({
          level: 2, // 第二层level为2
          positionInformation: item
        });

        item.isEdit = false;
        item.key = index;
        item.collectionId = collectionId;
        store.tabList.push(item);

        // 如果是最后一个则新增进去
        if (index === defaultCollection.length - 1)
          store.tabList.push({
            name: '新增',
            key: -1,
            isEdit: false,
            sort: -1
          });
      });

      // store.tabList[0].collectionId = collectionId;
      console.log(store.tabList);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

let setUpFormRef = ref(); // 储存setUpForm的ref

// 点击最上面的menu
const menuItemClick = (key: any) => {
  menuSelected.value = key;
};

const formData = ref(clonedeep(props.data)); // 储存传进来的值
// const formData = ref(clonedeep(props.data)); // 储存传进来的值

// 2保存或新增（有id是编辑，无id是新增）1渲染表单
const chagangetest = (type: number) => {
  console.log(setUpFormRef.value.copySetUpList);
  // console.log(setUpFormRef.value.centerRef.tabList);

  formData.value = setUpFormRef.value.copySetUpList;
  if (type === 1) return; // 如果是渲染，则不读数据库
  mitter.on('tabsChange', (res) => {
    console.log(res);
  });
  // 把对象转成字符串，boolean转0/1
  formData.value.forEach((item: any) => {
    item.props = JSON.stringify(item.props);
    item.required = item?.required ? 1 : 0;
    item.show = item.show ? 1 : 0;
    item.values = JSON.stringify(item.values);
  });
  emit('saveForm', formData.value);
  // visible.value = false;
};
// const chagangetest = (type: number) => {
//   formData.value.form = setUpFormRef.value.copySetUpList.map((item: any) => {
//     return {
//       ...item,
//       props: JSON.stringify(item.props),
//       required: item?.required ? 1 : 0,
//       show: !!item.show,
//       values: JSON.stringify(item.values),
//     };
//   });
//   if (type !== 1) {
//     emit('saveForm', formData.value);
//     visible.value = false;
//   }
// };

const setUpList = ref([[]]);

// 当前选中tabs的index
let currIndex = ref(0);
let preId = 0; // 用来判断获取的数据是否和上一次的相同
// let isFirst = true; // 判断是否是第一次加载页面
watch(props.data, async (val: any) => {
  try {
    // getData();
    // 获取当前点击的子集index
    mitter.on('formTabChange', (res: any) => {
      currIndex.value = res;
    });
    val.list.positionCollectionModel.forEach((item: any) => {
      if (item.componentModel) {
        item.componentModel.forEach((item2: any, index2: number) => {
          item2.uuid = `${index2}`;
        });
      }
    });
    // 如果是编辑
    if (val.list.id) {
      store.templateId = val.list.id;
      baseSetting.value = val.list;
      formData.value = clonedeep(val.list.positionCollectionModel);

      setUpList.value = val.list.positionCollectionModel;

      console.log(setUpList.value);
      setUpFormRef.value.copySetUpList = val.list.positionCollectionModel;
      if (preId !== val.list.id) {
        store.tabList = [];
        val.list.positionCollectionModel.forEach((item: any, index: number) => {
          store.tabList.push(item);
          store.tabList[index].key = index;
        });
        store.tabList.push({
          name: '新增',
          key: -1,
          isEdit: false,
          sort: -1
        });
      }
      // else {
      //   console.log(77777777777);
      //   console.log(val.list.organizationTemplateModel.collectionModel);

      //   store.tabList = [];
      //   val.list.organizationTemplateModel.collectionModel.forEach(
      //     (item: any, index: number) => {
      //       store.tabList.push(item);
      //       store.tabList[index].key = index;
      //     }
      //   );
      //   store.tabList.push({
      //     name: '新增',
      //     key: -1,
      //     isEdit: false,
      //     sort: -1
      //   });
      // }
      // isFirst = false;
      preId = val.list.id;
    } else {
      console.log(baseSetting.value);

      // store.templateId = undefined;
      // store.tabList = [];
      // const collectionId = await PostTemplate({
      //   level: 2, // 第二层level为2
      //   information: {
      //     name: '基础信息',
      //     key: 0,
      //     isEdit: false,
      //     sort: 0,
      //     templateId: store.templateId
      //   }
      // });
      // store.tabList[0].collectionId = collectionId;
      // store.tabList.push({
      //   name: '新增',
      //   key: -1,
      //   isEdit: false,
      //   sort: -1
      // });
      formData.value = clonedeep(val.list.positionCollectionModel);
      setUpList.value = val.list.positionCollectionModel;
      setUpFormRef.value.copySetUpList = val.list.positionCollectionModel;
    }
  } catch (error) {
    console.log(error);
  }

  // formData.value.form = setUpFormRef.value.copySetUpList;
});

onMounted(() => {
  // baseSetting.value.type = formData.value.type;
});

// 暴露方法给父组件
defineExpose({ fullScreen });
</script>

<style scoped lang="less">
.header {
  display: flex;
  border-bottom: 1px solid #eee;
  align-items: center;

  .form-name {
    font-size: 18px;
  }

  // background: rgba(61, 126, 255, 1);
  // color: white;
  .menu {
    flex: 1;
    text-align: center;
  }
}

.content {
  height: 100vh;

  .main {
    height: 100%;
    background: #eee;

    .base {
      background-color: #fff;
      height: 100%;
      :deep(.arco-form-item-label-col > .arco-form-item-label) {
        font-size: 16px;
      }
      &-form {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        width: 50%;
        margin-top: 20px;
        font-weight: 700;
      }
    }

    .print-set {
      display: flex;
      height: 100%;

      .form-check {
        width: 300px;
        background: white;
        height: 100%;
        margin: 16px 0;
        overflow: auto;

        .check-item {
          display: flex;
          justify-content: space-between;
          padding: 16px;
        }
      }

      .form {
        width: 700px;
        height: 1000px;
        overflow: auto;
        margin: 20px auto;
        padding: 16px;
        background: white;
      }
    }
  }
}
</style>
